<template>
  <div class="user-management">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input
              v-model="searchForm.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.state"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="action-area mb-20">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <!-- <el-button
          type="danger"
          :disabled="!selectedIds.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button> -->
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="roleName" label="角色" />
        <el-table-column prop="mchNO" label="商户号" />
        <el-table-column prop="rate" label="汇率">
          <template #default="{ row }">
            {{ row.rate / 100 }}
          </template>
        </el-table-column>
        <el-table-column prop="privateKey" label="私钥" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="cTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTimestamp(row.cTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.state === 0 ? 'success' : 'danger'">
              {{ row.state === 0 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleResetKey(row)">
              重置密钥
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增用户"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="角色" prop="roleID">
          <el-select v-model="formData.roleID" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
            v-model="formData.pwd"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="APPID" prop="appID">
          <el-input v-model="formData.appID" placeholder="请输入APPID" />
        </el-form-item>
        <el-form-item label="商户号" prop="mchNo">
          <el-input v-model="formData.mchNo" placeholder="请输入商户号" />
        </el-form-item>
        <el-form-item label="支付通道" prop="paymentID">
          <el-input v-model="formData.paymentID" placeholder="请输入支付通道" />
        </el-form-item>
        <el-form-item label="汇率" prop="rate">
          <el-input v-model="formData.rate" placeholder="请输入汇率" />
        </el-form-item>
        <el-form-item label="私钥" prop="privateKey">
          <el-input v-model="formData.privateKey" placeholder="请输入私钥" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="锁定" prop="locked">
          <el-radio-group v-model="formData.locked">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.state">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    <!-- 编辑用户表单对话框 -->
    <el-dialog
      v-model="UpdateDialogVisible"
      title="编辑用户"
      width="600px"
      @close="handleDialogCloseUpdate"
    >
      <el-form
        ref="UpdateFormRef"
        :model="updateFormData"
        :rules="updateFormRules"
        label-width="100px"
      >
        <el-form-item label="角色" prop="roleID">
          <el-select v-model="updateFormData.roleID" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="updateFormData.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="updateFormData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateFormData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="支付通道" prop="paymentID">
          <el-input
            v-model="updateFormData.paymentID"
            placeholder="请输入支付通道"
          />
        </el-form-item>
        <el-form-item label="账户金额" prop="amount">
          <el-input
            v-model="updateFormData.amount"
            placeholder="请输入账户金额"
          />
        </el-form-item>
        <el-form-item label="上级代理商" prop="parent">
          <el-input
            v-model="updateFormData.parent"
            placeholder="请输入上级代理商"
          />
        </el-form-item>
        <el-form-item label="汇率" prop="rate">
          <el-input v-model="updateFormData.rate" placeholder="请输入汇率" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="updateFormData.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="锁定" prop="locked">
          <el-radio-group v-model="updateFormData.locked">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="updateFormData.state">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item> </el-form
      ><template #footer>
        <el-button @click="handleDialogCloseUpdate">取消</el-button>
        <el-button
          type="primary"
          @click="handleUpdateSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    <!-- 设置角色对话框 -->
    <el-dialog
      v-model="RoleDialogVisible"
      title="设置角色"
      width="600px"
      @close="handleRoleDialogClose"
    >
      <el-form :model="RoleFormData" :rules="RoleFormRules" ref="RoleFormRef">
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="RoleFormData.roleIds"
            placeholder="请选择角色"
            multiple
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleRoleDialogClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmitRole"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户密钥 -->
    <el-dialog
      v-model="keyDialogVisible"
      title="用户密钥"
      width="600px"
      @close="handleKeyDialogClose"
    >
      <el-form ref="keyFormRef">
        <el-form-item label="用户ID" prop="id">
          <span>请妥善保管密钥</span>
        </el-form-item>
        <el-form-item label="用户密钥" prop="key">
         <div style="display: flex;">
           <el-input
            v-model="userGoogleKey"
            placeholder="用户密钥"
            :disabled="true"
            style="width: 350px;"
          >
          </el-input>
          <el-button slot="append" type="primary" @click="copyKey">
            复制
          </el-button>
         </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="handleKeyDialogClose"
          :loading="submitLoading"
        >
          我已保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import {
  getAccountList,
  getRoleList,
  grantRolePermissions,
  createAccount,
  updateAccount,
  deleteAccount,
  resetUserKey,
} from "@/api/system";
import type { Account, AccountListParams, Role } from "@/api/types";

// 搜索表单
const searchForm = reactive({
  email: "",
  // parent: 0,
  phone: "",
  // rate: 0,
  state: 0,
  username: "",
});

// 密钥
const userGoogleKey = ref("");
const keyDialogVisible = ref(false);

// 表格数据
const tableData = ref<Account[]>([]);

const loading = ref(false);
// 角色列表数据
const roleList = ref<Role[]>([]);
// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const RoleDialogVisible = ref(false);
const submitLoading = ref(false);

// 表单
const formRef = ref<FormInstance>();
const formData = reactive({
  appID: "",
  email: "",
  locked: 0,
  mchNo: "",
  parent: 0,
  paymentID: 0,
  phone: "",
  privateKey: "",
  pwd: "",
  rate: 0,
  remark: "",
  roleID: 4,
  state: 0,
  username: "",
});

const formRules: FormRules = {
  roleID: [{ required: true, message: "请选择角色", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  email: [
    { required: false, message: "请输入邮箱", trigger: "blur" },
    // 加上正则，合法的邮箱
    {
      pattern:
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, message: "密码长度不能少于5位", trigger: "blur" },
  ],
  rate: [{ required: true, message: "请输入费率", trigger: "blur" }],
};

// 重置谷歌密钥
const handleResetKey = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要重置${row.username}密钥吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    const res: any = await resetUserKey({ uid: row.id });
    console.log(res);
    ElMessage.success("重置成功");
    // 重置密钥
    userGoogleKey.value = res.data.secret;
    keyDialogVisible.value = true;
  } catch (error) {
    return;
  }
};

// 密钥弹窗关闭
const handleKeyDialogClose = () => {
  keyDialogVisible.value = false;
};
// 复制密钥
const copyKey = () => {
  // 点击复制密钥
  if (userGoogleKey.value) {
    // 复制密钥
    navigator.clipboard.writeText(userGoogleKey.value);
    ElMessage.success("复制成功");
  }
};

// 更新用户相关
const UpdateDialogVisible = ref(false);
const UpdateFormRef = ref<FormInstance>();
const updateFormData = reactive({
  id: 0,
  amount: 0,
  email: "",
  locked: 0,
  parent: 0,
  paymentID: 0,
  phone: "",
  rate: 0,
  remark: "",
  roleID: 4,
  state: 0,
  username: "",
});
// 保存原始数据用于比较
const originalData = ref<any>({});
const updateFormRules: FormRules = {
  roleID: [{ required: true, message: "请选择角色", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  email: [
    { required: false, message: "请输入邮箱", trigger: "blur" },
    // 加上正则，合法的邮箱
    {
      pattern:
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  rate: [{ required: true, message: "请输入费率", trigger: "blur" }],
};
const handleDialogCloseUpdate = () => {
  UpdateFormRef.value?.resetFields();
  UpdateDialogVisible.value = false;
};

const handleEdit = (row: Account) => {
  Object.assign(updateFormData, { ...row });
  updateFormData.rate = row.rate ? row.rate / 100 : 0;
  // 保存原始数据
  originalData.value = { ...row };
  UpdateDialogVisible.value = true;
};

const handleUpdateSubmit = async () => {
  if (!UpdateFormRef.value) return;
  try {
    await UpdateFormRef.value.validate();
    const params = {
      amount: updateFormData.amount,
      email: updateFormData.email,
      locked: updateFormData.locked,
      parent: updateFormData.parent,
      paymentID: updateFormData.paymentID,
      phone:
        updateFormData.phone === originalData.value.phone
          ? ""
          : updateFormData.phone,
      rate: updateFormData.rate,
      remark: updateFormData.remark,
      roleID: updateFormData.roleID,
      state: updateFormData.state,
      username: updateFormData.username,
      id: updateFormData.id,
    };
    const res: any = await updateAccount(params);
    if (res.code === 0) {
      ElMessage.success("更新用户成功");
      handleDialogCloseUpdate();
      loadData();
    }
  } catch (error) {
    return;
  }
};

// 角色相关
// 角色表单数据
const RoleFormData = reactive({
  roleIds: [1] as number[],
  uid: null as number | null,
});
const RoleFormRef = ref<FormInstance>();
const RoleFormRules: FormRules = {
  roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
};
// 获取角色列表
const LoadRoleList = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.page,
      size: pagination.size,
      name: "",
    };

    const response = await getRoleList(params);
    roleList.value = response.data.data || [];
  } catch (error) {
    console.error("加载角色列表失败:", error);
    ElMessage.error("加载角色列表失败");
  } finally {
    loading.value = false;
  }
};
LoadRoleList();
// 关闭角色对话框
const handleRoleDialogClose = () => {
  RoleFormRef.value?.resetFields();
  RoleFormData.roleIds = [];
  RoleFormData.uid = 0;
  RoleDialogVisible.value = false;
};

// 打开角色对话框
// const handleEditRole = async (row: Account) => {
//   RoleFormData.uid = row.id;
//   RoleDialogVisible.value = true;
// };

// 提交角色
const handleSubmitRole = async () => {
  if (!RoleFormRef.value) return;
  try {
    await RoleFormRef.value.validate();
    const params = {
      uid: RoleFormData.uid,
      roleIds: RoleFormData.roleIds,
    };
    console.log(params);
    const res: any = await grantRolePermissions(params);
    if (res.code === 0) {
      ElMessage.success("设置角色成功");
      handleRoleDialogClose();
      loadData();
    }
  } catch (error) {
    return;
  }
};

// 时间戳格式化函数
const formatTimestamp = (timestamp: number | string) => {
  if (!timestamp) return "-";

  // 如果是字符串类型的时间戳，转换为数字
  const time = typeof timestamp === "string" ? parseInt(timestamp) : timestamp;

  // 如果时间戳是秒级（10位），转换为毫秒级
  const date = new Date(time.toString().length === 10 ? time * 1000 : time);

  // 格式化为 YYYY-MM-DD HH:mm:ss
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: "",
    email: "",
    phone: "",
    state: 0,
  });
  handleSearch();
};

// 加载数据
const loadData = async () => {
  try {
    loading.value = true;
    const params: AccountListParams = {
      page: pagination.page,
      size: pagination.size,
      username: searchForm.username || undefined,
      email: searchForm.email || undefined,
      phone: searchForm.phone || undefined,
      state: searchForm.state ? Number(searchForm.state) : undefined,
    };

    const result = await getAccountList(params);
    tableData.value = result.data.data;
    pagination.total = result.data.total;
  } catch (error) {
    console.error("获取账户列表失败:", error);
    ElMessage.error("获取账户列表失败");
  } finally {
    loading.value = false;
  }
};

// 新增
const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

// 编辑

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户"${row.username}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const res: any = await deleteAccount({ id: row.id });
        if (res.code === 0) {
          ElMessage.success("删除成功");
          loadData(); // 重新加载数据
        }
      })
      .catch(() => {
        console.log("已取消删除");
      });
  } catch {
    // 用户取消
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadData();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    formData.rate = Number(formData.rate);
    // 新增
    const res: any = await createAccount(formData as Account);
    if (res.code === 0) {
      ElMessage.success(res.msg);
      dialogVisible.value = false;
      loadData();
      userGoogleKey.value = res.data.googleSecret;
      keyDialogVisible.value = true;
    }
  } catch (error) {
    console.error("提交失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 对话框关闭
const handleDialogClose = () => {
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    username: "",
    nickname: "",
    email: "",
    phone: "",
    pwd: "",
    state: 0,
  });
  formRef.value?.resetFields();
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.user-management {
  padding: 0;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.action-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}
</style>
